var express = require('express');
var router = express.Router();
var mongoose = require("../db/connect")
// const crypto = require('crypto');
// const jwt = require("jsonwebtoken");
// const request = require("request");
var path = require("path")
var fs = require("fs")
const formidable = require('formidable')

var Msg = mongoose.model('msg', {
  classes: Number,
  grades: Number,
  year: Number,
  height: Number,
  isMember: Boolean,
  hobby: Array,
  imgList: Array,
  name: String,
  birthday: String,
  describe: String,
  createTime: Number
})

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.post('/upload', (req, res) => {
  const form = formidable({ multiples: true });
  // const form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, "../public/upload/");
  form.parse(req, (err, fields, files) => {
    if (!files.file) return;  //没有上传文件，不进行任何处理
    //上传文件重命名
    fs.renameSync(files.file.path, form.uploadDir + files.file.name);
    res.status(200).json({
      code: 200,
      status: 0,
      msg: "上传图片成功",
      // result: `http://localhost:3000/upload/` + files.file.name
      result: `http://47.93.55.54:3300/upload/` + files.file.name
    })
  });
})

router.post('/addMsg', (req, res) => {
  new Msg({ ...req.body, createTime: new Date().getTime() }).save().then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response,
      message: "上传信息成功"
    })
  })
})

router.post('/deleteMsgById', (req, res) => {
  let obj = {};
  if (req.body.id) {
    obj._id = req.body.id
  }
  Msg.deleteOne(obj, { __v: 0 }).then(respons => {
    Msg.find({}, { __v: 0 }).then(response => {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "删除信息成功"
      })
    })
  })
})

router.post('/getMsgById', (req, res) => {
  let obj = {};
  if (req.body.id) {
    obj._id = req.body.id
  }
  Msg.findOne(obj, { __v: 0 }).then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response,
      message: "获取信息成功"
    })
  })
})

router.post('/getMsg', (req, res) => {
  let obj = {};
  if (req.body.name) {
    obj.name = RegExp(req.body.name)
  }
  Msg.find(obj, { __v: 0 }).then(response => {
    res.status(200).json({
      code: 200,
      status: 0,
      data: response,
      message: "获取信息成功"
    })
  })
})

router.post('/updateMsg', (req, res) => {

  let query = {_id: req.body._id};
  let update = {...req.body};
  delete update._id;
  let options = { upsert: true, new: true, setDefaultsOnInsert: true };

  //查找文档
  Msg.findOneAndUpdate(query, update, options, function (error, response) {
    if (!error) {
      res.status(200).json({
        code: 200,
        status: 0,
        data: response,
        message: "获取信息成功"
      })
    }
  });
})


module.exports = router;
